<?php

declare(strict_types=1);

namespace App\Controller;

use App\Constants\ErrorCode;
use App\Library\Common;
use App\Model\data\CurrentShopData;
use App\Service\FlyGourmetMealService;
use App\Service\FlyShopAdService;
use Hyperf\DbConnection\Db;
use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\HttpServer\Contract\ResponseInterface;
use Hyperf\Di\Annotation\Inject;
use Hyperf\Validation\Rule;

class ShopAdController extends AbstractController
{

    /**
     * @Inject
     * @var FlyShopAdService
     */
    protected $shopAdService;

//    推广列表
    public function index()
    {
        $param =  $this->request->inputs(['key_word','is_show']);
        $shop_info = CurrentShopData::getData();
        $return = $this->paginate($this->shopAdService->index($param,intval($shop_info->id)))->toArray();
        foreach ($return['data'] as $key=>$value){
            if(isset($value['commissions'])&&$value['commissions']!=''){
                $subtotal =  array_sum(array_column($value['commissions'],'subtotal'));
                $refund_subtotal =  array_sum(array_column($value['commissions'],'refund_subtotal'));
                array_column($value['commissions'],'refund_subtotal');
                $return['data'][$key]['real_total'] = $subtotal-$refund_subtotal;
            }else{
                $return['data'][$key]['real_total'] = 0;
            }
        }
        return $this->jsonResponse->success($return,'店铺推广列表');
    }

    //    查看店铺推广列表
    public function public_index()
    {
        $param =  $this->request->inputs(['key_word','is_show','shop_id']);
        $this->validation($param,
            [
                'shop_id'=>[
                    "integer",
                    "min:1",
                ],
            ]
        );
        $return = $this->paginate($this->shopAdService->index($param,intval($param['shop_id'])));
        return $this->jsonResponse->success($return,'推广列表');
    }

//   设置推广详情
    public function detail()
    {
        $id =  $this->request->input('id','');
        $lat = $this->request->input('lat','');
        $lng = $this->request->input('lng','');
        $this->validation([
                'id'=>$id,
                'lng'=>$lng,
                'lat'=>$lat
            ],
            [
                'id'=>[
                    "required",
                    "integer",
                    "min:1",
                    Rule::exists('fly_product')->whereNull('deleted_at'),
                ],
                'lng'=> 'numeric|min:0|max:180',
                'lat'=> 'numeric|min:-90|max:90',
            ]
        );
        return $this->jsonResponse->success($this->gourmetMeal->info(intval($id),$lng,$lat),'店铺美食详情');
    }
//
    public function add()
    {
        $shop_info = CurrentShopData::getData();
        $request_p =  $this->request->inputs(['radio','product_ids']);
        $this->validation($request_p,
            [
                'radio'=>["required","numeric","min:0.01","max:99.99",],
                'product_ids'=>[
                    "required",
                    "array",
                    "min:1",
                ],
                'product_ids.*'=> [
                    "required",
                    "integer",
                    "distinct",
                    Rule::exists('fly_product','id')
                        ->where('is_show',1)
                        ->where('shop_id',$shop_info->id)
                        ->where('check_status',1)
                        ->where('is_illegal',0)
                        ->whereNull('deleted_at'),
                    Rule::exists('fly_sku','product_id'),
                    Rule::unique('fly_shop_ad','product_id')->whereNull('deleted_at'),
                ],
            ],
            [
              'product_ids.*.exists'=>  '商品不存在或不完整sku或未上架',
              'product_ids.*.unique'=>  '商品已设置推广，请检查'
            ],
        );
        Db::beginTransaction();
        try {
            $request_p['created_at'] = Common::date_time(2);
            $request_p['create_by'] = $this->getAdminId();
            $res = $this->shopAdService->add(intval($shop_info->id),$request_p);
            if($res){
                Db::commit();
                return $this->jsonResponse->success($res,'添加成功');
            }else{
                Db::rollBack();
                return $this->jsonResponse->error(ErrorCode::SYSTEM_INVALID,'添加失败1');
            }
        } catch (\Throwable $exception) {
            Db::rollBack();
            return $this->jsonResponse->error(ErrorCode::SYSTEM_INVALID,'添加失败2'.$exception->getMessage());
        }
    }

    public function edit()
    {
        $shop_info = CurrentShopData::getData();
        $request_p =  $this->request->inputs(['id','radio','product_id']);
        $this->validation($request_p,
            [
                'id'=>[
                    "required",
                    "integer",
                    "min:1",
                    Rule::exists('fly_shop_ad','id'),
                ],
                'radio'=>[
                    "required",
                    "numeric",
                    "min:0.01",
                    "max:99.99",
                ],
                'product_id'=> [
                    "required",
                    "integer",
                    "distinct",
                    Rule::exists('fly_product','id')
                        ->where('is_show',1)
                        ->where('shop_id',$shop_info->id)
                        ->where('check_status',1)
                        ->where('is_illegal',0)->whereNull('deleted_at'),
                    Rule::exists('fly_sku','product_id'),
                    Rule::unique('fly_shop_ad','product_id')->whereNull('deleted_at')->ignore($request_p['id']),
                ],
            ],
            [
                'product_ids.exists'=>  '商品不存在或未上架',
                'product_ids.unique'=>  '商品已设置推广，请检查'
            ],
            );
        Db::beginTransaction();
        try {
            $request_p['updated_at'] = Common::date_time(2);
            $request_p['update_by'] = $this->getAdminId();
            $res = $this->shopAdService->edit($request_p);
            if($res){
                Db::commit();
                return $this->jsonResponse->success($res,'修改成功');
            }else{
                Db::rollBack();
                return $this->jsonResponse->error(ErrorCode::SYSTEM_INVALID,'修改失败');
            }
        } catch (\Throwable $exception) {
            Db::rollBack();
            return $this->jsonResponse->error(ErrorCode::SYSTEM_INVALID,'修改失败.'.$exception->getMessage());
        }
    }


    public function change_show()
    {
        $shop_info = CurrentShopData::getData();
        $request_p =  $this->request->inputs(['ids','is_show']);
        $this->validation($request_p,
            [
                'ids.*'=>[
                    "required",
                    "integer",
                    "min:1",
                    Rule::exists('fly_shop_ad','id'),
                ],
                'is_show' => 'required|boolean',
            ],
            );
        Db::beginTransaction();
        try {
            $res =  $this->shopAdService->change_show($request_p['ids'],boolval($request_p['is_show']),intval($this->getAdminId()));
            if($res){
                Db::commit();
                return $this->jsonResponse->success($res,'添加成功');
            }else{
                Db::rollBack();
                return $this->jsonResponse->error(ErrorCode::SYSTEM_INVALID,'添加失败1');
            }
        } catch (\Throwable $exception) {
            Db::rollBack();
            return $this->jsonResponse->error(ErrorCode::SYSTEM_INVALID,'添加失败2'.$exception->getMessage());
        }
    }

    public function del()
    {
        $ids = $this->request->input('ids');
        $shop_info = CurrentShopData::getData();
        $this->validation(
            ['ids'=>$ids],
            [
                'ids' => 'required|array',
                'ids.*' => [
                    'required',
                    'integer',
                    'min:0',
                    Rule::exists('fly_shop_ad','id')
                        ->where('shop_id',$shop_info->id)
                        ->whereNull('deleted_at'),
                ],
            ],
            [
                'ids.*.unique'  =>'有关联数据，不可删除',
            ]
        );
        try{
            $this->shopAdService->deleteByUser($ids,$this->getAdminId());
            return $this->jsonResponse->success([],'删除成功');
        } catch (\Throwable $exception) {
            return $this->jsonResponse->error(ErrorCode::SYSTEM_INVALID,'删除失败');
        }
    }

/***
 *                                         ,s555SB@@&
 *                                      :9H####@@@@@Xi
 *                                     1@@@@@@@@@@@@@@8
 *                                   ,8@@@@@@@@@B@@@@@@8
 *                                  :B@@@@X3hi8Bs;B@@@@@Ah,
 *             ,8i                  r@@@B:     1S ,M@@@@@@#8;
 *            1AB35.i:               X@@8 .   SGhr ,A@@@@@@@@S
 *            1@h31MX8                18Hhh3i .i3r ,A@@@@@@@@@5
 *            ;@&i,58r5                 rGSS:     :B@@@@@@@@@@A
 *             1#i  . 9i                 hX.  .: .5@@@@@@@@@@@1
 *              sG1,  ,G53s.              9#Xi;hS5 3B@@@@@@@B1
 *               .h8h.,A@@@MXSs,           #@H1:    3ssSSX@1
 *               s ,@@@@@@@@@@@@Xhi,       r#@@X1s9M8    .GA981
 *               ,. rS8H#@@@@@@@@@@#HG51;.  .h31i;9@r    .8@@@@BS;i;
 *                .19AXXXAB@@@@@@@@@@@@@@#MHXG893hrX#XGGXM@@@@@@@@@@MS
 *                s@@MM@@@hsX#@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@&,
 *              :GB@#3G@@Brs ,1GM@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@B,
 *            .hM@@@#@@#MX 51  r;iSGAM@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@8
 *          :3B@@@@@@@@@@@&9@h :Gs   .;sSXH@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@:
 *      s&HA#@@@@@@@@@@@@@@M89A;.8S.       ,r3@@@@@@@@@@@@@@@@@@@@@@@@@@@r
 *   ,13B@@@@@@@@@@@@@@@@@@@5 5B3 ;.         ;@@@@@@@@@@@@@@@@@@@@@@@@@@@i
 *  5#@@#&@@@@@@@@@@@@@@@@@@9  .39:          ;@@@@@@@@@@@@@@@@@@@@@@@@@@@;
 *  9@@@X:MM@@@@@@@@@@@@@@@#;    ;31.         H@@@@@@@@@@@@@@@@@@@@@@@@@@:
 *   SH#@B9.rM@@@@@@@@@@@@@B      @@@          3@@@@@@@@@@@@@@@@@@@@@@@@@@5
 *     ,:.   9@@@@@@@@@@@#HB5   @@@@@           .M@@@@@@@@@@@@@@@@@@@@@@B
 *           ,ssirhSM@&1;i19911i,.             s@@@@@@@@@@@@@@@@@@@@@@@@@@S
 *              ,,,rHAri1h1rh&@#353Sh:          8@@@@@@@@@@@@@@@@@@@@@@@@@#:
 *            .A3hH@#5S553&@@#h   i:i9S          #@@@@@@@@@@@@@@@@@@@@@@@@@A.
 *
 *
 *    妈妈，再爱我一次！
 */
}
